"""
均线分析模块
专门针对移动平均线的深度分析
"""

import pandas as pd
import numpy as np
from typing import Dict, List, Tuple


class MAAnalyzer:
    """均线深度分析类"""
    
    @staticmethod
    def analyze_ma_arrangement(df: pd.DataFrame) -> Dict:
        """
        分析均线排列
        多头排列：短期均线 > 中期均线 > 长期均线（看涨）
        空头排列：短期均线 < 中期均线 < 长期均线（看跌）
        """
        if len(df) < 20:
            return {}
        
        latest = df.iloc[-1]
        result = {}
        
        # 检查关键均线是否存在
        has_ma5 = 'MA5' in latest and pd.notna(latest['MA5'])
        has_ma10 = 'MA10' in latest and pd.notna(latest['MA10'])
        has_ma20 = 'MA20' in latest and pd.notna(latest['MA20'])
        has_ma60 = 'MA60' in latest and pd.notna(latest['MA60'])
        
        if not (has_ma5 and has_ma10 and has_ma20):
            return result
        
        current_price = latest['收盘']
        ma5 = latest['MA5']
        ma10 = latest['MA10']
        ma20 = latest['MA20']
        
        # 短期均线排列（5/10/20）
        if ma5 > ma10 > ma20 > current_price * 0.95:  # 允许5%容差
            result['短期排列'] = "多头排列"
            result['短期信号'] = "🚀 强势上涨排列"
            result['短期状态'] = "bullish"
        elif ma5 < ma10 < ma20:
            result['短期排列'] = "空头排列"
            result['短期信号'] = "⚠️ 弱势下跌排列"
            result['短期状态'] = "bearish"
        else:
            result['短期排列'] = "缠绕"
            result['短期信号'] = "📊 均线缠绕，方向不明"
            result['短期状态'] = "neutral"
        
        # 如果有60日线，分析中长期排列
        if has_ma60:
            ma60 = latest['MA60']
            if ma5 > ma10 > ma20 > ma60:
                result['中期排列'] = "完美多头"
                result['中期信号'] = "✅ 完美多头排列，趋势强劲"
            elif ma5 < ma10 < ma20 < ma60:
                result['中期排列'] = "完美空头"
                result['中期信号'] = "❌ 完美空头排列，趋势疲弱"
        
        # 价格与均线关系
        ma_positions = []
        if current_price > ma5:
            ma_positions.append("站上MA5")
        if current_price > ma10:
            ma_positions.append("站上MA10")
        if current_price > ma20:
            ma_positions.append("站上MA20")
        
        if len(ma_positions) >= 3:
            result['价格位置'] = "站上所有短期均线"
            result['价格信号'] = "✅ 强势"
        elif len(ma_positions) >= 2:
            result['价格位置'] = "站上部分均线"
            result['价格信号'] = "📊 中性"
        elif len(ma_positions) >= 1:
            result['价格位置'] = "仅站上MA5"
            result['价格信号'] = "⚠️ 偏弱"
        else:
            result['价格位置'] = "跌破所有均线"
            result['价格信号'] = "❌ 弱势"
        
        return result
    
    @staticmethod
    def analyze_ma_cross(df: pd.DataFrame) -> Dict:
        """
        分析均线金叉死叉
        """
        if len(df) < 10:
            return {}
        
        result = {}
        latest = df.iloc[-1]
        prev = df.iloc[-2]
        
        # MA5与MA10金叉死叉
        if 'MA5' in latest and 'MA10' in latest:
            if pd.notna(latest['MA5']) and pd.notna(latest['MA10']):
                # 检测金叉
                if prev['MA5'] <= prev['MA10'] and latest['MA5'] > latest['MA10']:
                    result['MA5_MA10'] = "金叉"
                    result['MA5_MA10_信号'] = "🔥 MA5金叉MA10（买入信号）"
                    result['MA5_MA10_状态'] = "golden_cross"
                # 检测死叉
                elif prev['MA5'] >= prev['MA10'] and latest['MA5'] < latest['MA10']:
                    result['MA5_MA10'] = "死叉"
                    result['MA5_MA10_信号'] = "⚠️ MA5死叉MA10（卖出信号）"
                    result['MA5_MA10_状态'] = "death_cross"
                # 判断当前状态
                elif latest['MA5'] > latest['MA10']:
                    diff_pct = (latest['MA5'] - latest['MA10']) / latest['MA10'] * 100
                    result['MA5_MA10'] = "多头"
                    result['MA5_MA10_信号'] = f"✅ MA5在MA10上方（乖离{diff_pct:.2f}%）"
                    result['MA5_MA10_状态'] = "bullish"
                else:
                    diff_pct = (latest['MA10'] - latest['MA5']) / latest['MA10'] * 100
                    result['MA5_MA10'] = "空头"
                    result['MA5_MA10_信号'] = f"⚠️ MA5在MA10下方（乖离{diff_pct:.2f}%）"
                    result['MA5_MA10_状态'] = "bearish"
        
        # MA10与MA20金叉死叉
        if 'MA10' in latest and 'MA20' in latest:
            if pd.notna(latest['MA10']) and pd.notna(latest['MA20']):
                if prev['MA10'] <= prev['MA20'] and latest['MA10'] > latest['MA20']:
                    result['MA10_MA20'] = "金叉"
                    result['MA10_MA20_信号'] = "🚀 MA10金叉MA20（中期买入）"
                elif prev['MA10'] >= prev['MA20'] and latest['MA10'] < latest['MA20']:
                    result['MA10_MA20'] = "死叉"
                    result['MA10_MA20_信号'] = "❌ MA10死叉MA20（中期卖出）"
                elif latest['MA10'] > latest['MA20']:
                    result['MA10_MA20'] = "多头"
                    result['MA10_MA20_信号'] = "✅ MA10在MA20上方"
                else:
                    result['MA10_MA20'] = "空头"
                    result['MA10_MA20_信号'] = "⚠️ MA10在MA20下方"
        
        return result
    
    @staticmethod
    def analyze_ma_support_resistance(df: pd.DataFrame) -> Dict:
        """
        分析均线支撑压力
        """
        if len(df) < 20:
            return {}
        
        latest = df.iloc[-1]
        current_price = latest['收盘']
        result = {}
        
        # 找出最近的支撑和压力均线
        ma_lines = {}
        for period in [5, 10, 20, 60]:
            col_name = f'MA{period}'
            if col_name in latest and pd.notna(latest[col_name]):
                ma_lines[period] = latest[col_name]
        
        if not ma_lines:
            return result
        
        # 分类支撑和压力
        support_mas = {k: v for k, v in ma_lines.items() if v < current_price}
        resistance_mas = {k: v for k, v in ma_lines.items() if v > current_price}
        
        if support_mas:
            # 找最近的支撑（最大的那个）
            nearest_support_period = max(support_mas.keys(), key=lambda k: support_mas[k])
            nearest_support = support_mas[nearest_support_period]
            distance_pct = (current_price - nearest_support) / current_price * 100
            
            result['最近支撑'] = f"MA{nearest_support_period}"
            result['支撑价位'] = f"¥{nearest_support:.2f}"
            result['支撑距离'] = f"{distance_pct:.2f}%"
            
        if resistance_mas:
            # 找最近的压力（最小的那个）
            nearest_resistance_period = min(resistance_mas.keys(), key=lambda k: resistance_mas[k])
            nearest_resistance = resistance_mas[nearest_resistance_period]
            distance_pct = (nearest_resistance - current_price) / current_price * 100
            
            result['最近压力'] = f"MA{nearest_resistance_period}"
            result['压力价位'] = f"¥{nearest_resistance:.2f}"
            result['压力距离'] = f"{distance_pct:.2f}%"
        
        # 均线密集度分析
        if len(ma_lines) >= 3:
            ma_values = list(ma_lines.values())
            ma_range = max(ma_values) - min(ma_values)
            ma_avg = sum(ma_values) / len(ma_values)
            concentration = ma_range / ma_avg * 100
            
            if concentration < 3:
                result['均线状态'] = "极度密集"
                result['状态评价'] = "🔥 均线粘合，即将变盘"
            elif concentration < 5:
                result['均线状态'] = "密集"
                result['状态评价'] = "⚡ 均线接近，关注突破方向"
            elif concentration < 10:
                result['均线状态'] = "正常发散"
                result['状态评价'] = "📊 均线排列正常"
            else:
                result['均线状态'] = "过度发散"
                result['状态评价'] = "⚠️ 均线过度发散，可能回归"
        
        return result
    
    @staticmethod
    def calculate_ma_score(df: pd.DataFrame) -> Tuple[float, List[str]]:
        """
        基于均线系统计算评分
        """
        if len(df) < 20:
            return 50.0, ["数据不足"]
        
        score = 50  # 基准分
        signals = []
        
        # 获取均线排列分析
        arrangement = MAAnalyzer.analyze_ma_arrangement(df)
        
        # 均线排列加分
        if arrangement.get('短期状态') == 'bullish':
            score += 20
            signals.append("✅ 短期均线多头排列")
        elif arrangement.get('短期状态') == 'bearish':
            score -= 15
            signals.append("⚠️ 短期均线空头排列")
        
        if arrangement.get('中期排列') == '完美多头':
            score += 15
            signals.append("🚀 完美多头排列")
        elif arrangement.get('中期排列') == '完美空头':
            score -= 15
            signals.append("❌ 完美空头排列")
        
        # 价格位置加分
        if arrangement.get('价格位置') == '站上所有短期均线':
            score += 10
            signals.append("✅ 价格站上所有短期均线")
        elif arrangement.get('价格位置') == '跌破所有均线':
            score -= 10
            signals.append("⚠️ 价格跌破所有均线")
        
        # 金叉死叉加分
        cross = MAAnalyzer.analyze_ma_cross(df)
        
        if cross.get('MA5_MA10_状态') == 'golden_cross':
            score += 15
            signals.append("🔥 MA5金叉MA10")
        elif cross.get('MA5_MA10_状态') == 'death_cross':
            score -= 15
            signals.append("⚠️ MA5死叉MA10")
        
        if cross.get('MA10_MA20') == '金叉':
            score += 10
            signals.append("🚀 MA10金叉MA20")
        elif cross.get('MA10_MA20') == '死叉':
            score -= 10
            signals.append("❌ MA10死叉MA20")
        
        # 均线密集度
        support_resistance = MAAnalyzer.analyze_ma_support_resistance(df)
        if support_resistance.get('均线状态') == '极度密集':
            score += 5
            signals.append("🔥 均线粘合，变盘在即")
        
        # 标准化分数
        final_score = max(0, min(100, score))
        
        return final_score, signals

